<template>
    <Dialog v-model="dialogVisible" title="教师导入" width="800">
        <el-upload
            ref="uploadRef"
            v-model:file-list="fileList"
            :action="importUrl"
            :auto-upload="false"
            :disabled="formLoading"
            :headers="uploadHeaders"
            :limit="1"
            :on-error="submitFormError"
            :on-exceed="handleExceed"
            :on-success="submitFormSuccess"
            accept=".xlsx, .xls"
            drag
        >
            <Icon icon="ep:upload"/>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            <template #tip>
                <div class="el-upload__tip text-center">
                    <span>仅允许导入 xls、xlsx 格式文件。</span>
                </div>
            </template>
        </el-upload>

        <el-card shadow="never" class="mb-5">
            <el-button :disabled="formLoading" type="success" @click="submitForm">开始上传</el-button>
            <el-button type="warning" @click="resetForm">清空列表</el-button>

            <el-button type="danger" @click="exportMissed" style="float: right" :loading="exportLoading">导出失败信息</el-button>
            <el-button type="primary" @click="importTemplate" style="float: right">下载模板</el-button>
        </el-card>

        <el-result v-if="isSuccess" icon="success" title="完成" sub-title="您已成功导入教师信息" style="height: 320px">
            <template #extra>
                <el-button type="primary" @click="onCancel">刷新查看</el-button>
            </template>
        </el-result>

        <el-table v-else :data="result" height="320px" v-loading="formLoading">
            <el-table-column type="index" label="Sn"/>
            <el-table-column label="教师姓名" prop="name" width="150" show-overflow-tooltip/>
            <el-table-column label="手机号" prop="mobile" width="200"/>
            <el-table-column label="失败原因" prop="message" min-width="360"/>
        </el-table>

        <template #footer>
            <el-button text bg type="danger" style="float: left">共计 {{ result.length }} 条异常信息</el-button>
            <el-button @click="onCancel">取 消</el-button>
        </template>
    </Dialog>
</template>

<script lang="ts" setup>
import {getAccessToken, getTenantId} from '@/utils/auth'
import download from '@/utils/download'
import {useConfirm, useMessage} from "@/components/Notice";
import {useMemberApi} from "@/api/yxt/member";
import {genFileId} from "element-plus";
import * as XLSX from "xlsx";
import {isEmpty} from "lodash-es";

defineOptions({name: 'YxtTeaImportForm'})

const memberApi = useMemberApi();

const dialogVisible = ref<boolean>(false)
const formLoading = ref<boolean>(false)
const uploadRef = ref<any>()
const importUrl = import.meta.env.VITE_BASE_URL + import.meta.env.VITE_API_URL + '/yxt/member/import/1';
const uploadHeaders = ref() // 上传 Header 头
const fileList = ref<Array<any>>([])
const result = ref<Array<any>>([])
const isSuccess = ref<boolean>(false)

const open = () => {
    dialogVisible.value = true
    resetForm()
}
defineExpose({open})

const submitForm = async () => {
    if (fileList.value.length == 0) {
        return useMessage("请上传文件", "error");
    }

    uploadHeaders.value = {
        Authorization: 'Bearer ' + getAccessToken(),
        'tenant-id': getTenantId()
    }
    formLoading.value = true;
    isSuccess.value = false;
    uploadRef.value!.submit();
}

const emits = defineEmits(['success'])
const submitFormSuccess = (response: any) => {
    if (response.code !== 0) {
        formLoading.value = false;
        return useMessage(response.msg, "error");
    }
    formLoading.value = false;
    result.value = response.data;
    resetList();
    if (isEmpty(result.value)) isSuccess.value = true;
}

const onCancel = () => {
    resetForm();
    emits('success');
    dialogVisible.value = false;
}
const submitFormError = (): void => {
    formLoading.value = false;
    useMessage("上传失败，请您重新上传！", "error");
}

const resetForm = () => {
    result.value = [];
    isSuccess.value = false;
    formLoading.value = false;
    uploadRef.value?.clearFiles()
}

const resetList = () => {
    uploadRef.value?.clearFiles();
}

const handleExceed = (files): void => {
    uploadRef.value!.clearFiles();
    const file = files[0];
    file.uid = genFileId();
    uploadRef.value!.handleStart(file);
}

const formatData = (item: any) => {
    return {
        "教师姓名": item.name,
        "手机号": item.mobile,
        "失败原因": item.message
    }
}

const exportLoading = ref<boolean>(false);
const exportMissed = () => {
    useConfirm("确认导出失败数据?", () => {
        exportLoading.value = true;
        try {
            if (result.value.length == 0) return useMessage("没有可导出异常数据", "error");

            const formData = result.value.map(formatData);
            // 创建工作簿
            const wb = XLSX.utils.book_new();
            // 创建工作表
            const ws = XLSX.utils.json_to_sheet(formData);
            // 将工作表添加到工作簿
            XLSX.utils.book_append_sheet(wb, ws, "异常数据");
            // 生成文件
            XLSX.writeFile(wb, "教师异常数据.xlsx");
        } finally {
            exportLoading.value = false;
        }
    })
}

const importTemplate = async () => {
    const res = await memberApi.getTemplate(1);
    download.excel(res, '教师导入模版.xlsx');
}
</script>

<style lang="scss" scoped>
::v-deep(.el-upload-list) {
    height: 30px;
}
</style>
